package cn.hamster3.hamsterworld.thread;

import cn.hamster3.api.HamsterAPI;
import cn.hamster3.hamsterworld.core.DataManager;
import cn.hamster3.hamsterworld.data.WorldData;
import org.bukkit.World;
import org.bukkit.scheduler.BukkitRunnable;

public class RealTime extends BukkitRunnable {
    private DataManager dataManager;

    public RealTime(DataManager dataManager) {
        this.dataManager = dataManager;
    }

    /**
     * 获取当前时间与早上6点过去了多少毫秒
     *
     * @return 毫秒数
     */
    private static long getDayMillis() {
        long time = System.currentTimeMillis();
        // 时区: UTC+8
        time = time + 1000 * 60 * 60 * 8;

        time = time % 86400000;


        long zeroTick = 1000 * 60 * 60 * 6;

        if (time > zeroTick) {
            time = time - zeroTick;
        } else {
            time = time + 1000 * 60 * 60 * 18;
        }

        return time;
    }

    @Override
    public void run() {
        // 游戏中一天为24000ticks
        // 86400000/24000=3600
        long realTime = getDayMillis() / 3600;
        HamsterAPI.sendConsoleMessage("§a[HamsterWorld] 时间转换完成, Minecraft ticks为: %d", realTime);
        for (WorldData worldData : dataManager.getWorldData()) {
            if (!worldData.isRealTime()) {
                continue;
            }
            World world = worldData.getWorld();
            long fullTime = world.getFullTime();
            fullTime = fullTime - (fullTime % 24000) + realTime;
            world.setFullTime(fullTime);
        }
    }
}
